package com.atguigu.lease.web.app.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import com.atguigu.lease.model.enums.ItemType;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/*
    批量制造转换器
    枚举类转化器工厂 ！ 批量制造转化器
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    //制造转化器方法
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        //返回具体的转化器
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                //1.获取枚举的全部值
                ItemType.values(); // 枚举的.values获取全部值
                //2.循环获取枚举的getCode 和 source对象
                for (T enumConstant : targetType.getEnumConstants()) {
                    //3.如果相同直接返回
                    if (enumConstant.getCode() == Integer.parseInt(source)) {
                        return enumConstant;
                    }
                }
                //4.循环以后没有结果抛出异常
                throw new RuntimeException("参数非法异常");
            }
        };
    }
}
